
function reloadMedicine(){
   var filter    =   $("input:radio[name='filterRdb']:checked").val();
   /* var dateFrom  =   $("#start_dd").val() + "/" + $("#start_mm").val() + "/" + $("#start_yyyy").val();
   var dateTo    =   $("#end_dd").val() + "/" + $("#end_mm").val() + "/" + $("#end_yyyy").val();
   */
   showAjaxLoader('loaderDiv', 'actionButtonDiv', true);
   var dateFrom =   $('#startDate').val();
   var dateTo   =   $('#endDate').val();
   $.ajax ({       
        url:        "../TicketMedicine/ViewTicketMedicineDetail?set_ajax_view",
        data:       "ticketId=" + $('#ticketIdHdn').val() +
                    "&dateFrom=" + dateFrom +
                    "&dateTo=" + dateTo +
                    "&filter="  +  filter,
        dataType:   "html",
        beforeSend: function() {                    
            
        },
        complete:   function() {
                     
        },
        success:  function(data) {
            showAjaxLoader('loaderDiv', 'actionButtonDiv', false);
            $("#medicineContentDiv").html(data);
        }
    });
}

function showInputMedicinePage(){
     showAjaxLoader('loaderDiv', 'actionButtonDiv', true);     
    $.ajax ({       
        url:        "../TicketMedicine/InputTicketMedicine?set_ajax_view",
        data:       "ticketId="+$('#ticketIdHdn').val(),
        dataType:   "html",
        beforeSend: function() {                    
            
        },
        complete:   function() {
                     
        },
        success:  function(data) {
            showAjaxLoader('loaderDiv', 'actionButtonDiv', false);  
            $("#ticketMedicineDiv").html(data);       
        }
    });
}

function loadInputMedicineDetail() {
    showAjaxLoader('issueDateLoaderDiv', 'false', true);  
    $.ajax ({       
        url:        "../TicketMedicine/InputMedicineDetail?set_ajax_view",
        data:       "&ticketId=" + $('#ticketIdHdn').val() + 
                    "&issueDate=" + $('#issueDateLbx').val(), 
        dataType:   "html",
        beforeSend: function() {                    
            
        },
        complete:   function() {
                     
        },
        success:  function(data) {
            showAjaxLoader('issueDateLoaderDiv', 'false', false);  
            $("#inputMedicineContentDiv").html(data);       
        }
    });
}

function showViewPage(){     
    ticketId    =   $('#ticketIdHdn').val();
    showAjaxLoader('issueDateLoaderDiv', 'false', true);
    $.ajax ({       
        url:        "../TicketMedicine/ViewTicketMedicine",
        data:       "ticketId=" + ticketId + "&set_ajax_view",
        dataType:   "html",
        beforeSend: function() {                    
            
        },
        complete:   function() {
                     
        },
        success:  function(data) {
             $("#ticketMedicineDiv").html(data); 
        }
    });
}

function clearMedicineRow(index){
    $('#medId_' + index).val('');
    $('#medName_' + index).val('');
    $('#quanNum_' + index).val('');
    $('#quanTitle_' + index).val('');
    $('#unitPrice_' + index).val('');
    $('#orgPrice_' + index).val('');
    $('#insPrice_' + index).val('');
    $('#patPrice_' + index).val('');
    $('#issuePersonName_' + index).text('');
    $('#issuePerson_' + index).val('');
     $('#doctorName_' + index).text('');
    $('#doctor_' + index).val('');
}

function clearMaterialRow(index){
    $('#matId_' + index).val('');
    $('#matName_' + index).val('');
    $('#matQuanNum_' + index).val('');
    $('#matQuanTitle_' + index).val('');
    $('#matUnitPrice_' + index).val('');
    $('#matOrgPrice_' + index).val('');
    $('#matInsPrice_' + index).val('');
    $('#matPatPrice_' + index).val('');
    $('#matIssuePersonName_' + index).text('');
    $('#matIssuePerson_' + index).val('');
    $('#matDoctorName_' + index).text('');
    $('#matDoctor_' + index).val('');
}

function getItemInfo(itemType, index) {
    if (!checkDoctorSelected() || !checkIssuePersonSelected()){
        return;
    }
    if (itemType=='medicine') {                         	                            
        $.ajax({
            url:    "../TicketMedicine/GetMedicineInfo",
            data:   "ticketId=" + $('#ticketIdHdn').val() + 
                    "&medicineName=" + $('#medName_' + index).val() + "&set_ajax_view",
            dataType:   "json",
            success:  function(data) {              
                $('#medId_' + index).val(data.medicine_id);
	            $('#quanNum_' + index).val(data.quantity_num);
	            $('#quanTitle_' + index).val(data.quantity_title);
	            $('#unitPrice_' + index).val(data.unit_price);
	            $('#orgPrice_' + index).val(data.original_price);
	            $('#insPrice_' + index).val(data.insurance_price);
	            $('#unitInsPrice_' + index).val(data.insurance_price);
	            $('#patPrice_' + index).val(data.patient_price);
	            $('#issuePersonName_' + index).text($('#issuePersonLbx option:selected').attr('label'));
	            $('#issuePerson_' + index).val($('#issuePersonLbx').val());
	            $('#doctorName_' + index).text($('#doctorLbx option:selected').attr('label'));
	            $('#doctor_' + index).val($('#doctorLbx').val());
	            if(index==$('#medTbl tbody tr').length){
	               var newRow  =   createNewMedicineRow(index+1);
	               $('#medTbl tbody').append(newRow);
	               $('#medTbl tbody tr:last input.medName').autocomplete('../Prescription/getAllMedicineNames?set_ajax_view',
			            {
			                multiple: false,
			                matchContains: true,
			                autoFill: true,
			                cacheLength: 1,
			                formatItem: function(data, i, total) {      
			                    return data[0];
			                }
			            }
                   );
	            }
            }
        });
    }    
    else if (itemType=='material') {
        $.ajax({
            url:    "../TicketMedicine/GetMaterialInfo",
            data:   "ticketId=" + $('#ticketIdHdn').val() + 
                    "&materialName=" + $('#matName_' + index).val() + "&set_ajax_view",
            dataType:   "json",
            success:  function(data) {              
                $('#matId_' + index).val(data.medical_material_id);
                $('#matQuanNum_' + index).val(1);
                $('#matQuanTitle_' + index).val(data.unit);
                $('#matUnitPrice_' + index).val(data.unit_price);
                $('#matOrgPrice_' + index).val(data.original_price);
                $('#matInsPrice_' + index).val(data.insurance_price);
                $('#matUnitInsPrice_' + index).val(data.insurance_price);
                $('#matPatPrice_' + index).val(data.patient_price);
                $('#matIssuePersonName_' + index).text($('#issuePersonLbx option:selected').attr('label'));
                $('#matIssuePerson_' + index).val($('#issuePersonLbx').val());
                $('#matDoctorName_' + index).text($('#doctorLbx option:selected').attr('label'));
                $('#matDoctor_' + index).val($('#doctorLbx').val());     
                if(index==$('#matTbl tbody tr').length){
                   var newRow  =   createNewMaterialRow(index+1);
                   $('#matTbl tbody').append(newRow);
                   $('#matTbl tbody tr:last input.matName').autocomplete('../MedicalMaterial/GetAllMaterialNames?set_ajax_view',
                        {
                            multiple: false,
                            matchContains: true,
                            autoFill: true,
                            cacheLength: 1,
                            formatItem: function(data, i, total) {      
                                return data[0];
                            }
                        }
                   );
                }
            }
        });
    }
}

function checkDoctorSelected(){
    var doctorId    =   parseInt($('#doctorLbx').val());
    if (doctorId <= 0){
        $('#doctorLbx').css('border-color', 'red');
        $('#statusMessage').text(_('Not yet selected doctor'));
        return false;
    }
    else {
        $('#doctorLbx').css('border-color', '#AAA');
        $('#statusMessage').text('');
        return true;
    }
}

function checkIssuePersonSelected() {
     var issuePersonId    =   parseInt($('#issuePersonLbx').val());
    if (issuePersonId <= 0){
        $('#issuePersonLbx').css('border-color', 'red');
        $('#statusMessage').text(_('Not yet selected issue person'));
        return false;
    }
    else {
        $('#issuePersonLbx').css('border-color', '#AAA');
        $('#statusMessage').text('');
        return true;
    }
}

function validateMedicineElement(index, inputType){
    switch(inputType){
        case 'quantity_num':
            var lcInt = locale(decimalPoint, thousandSep, 0);
            var quantity = parseLcNum($('#quanNum_' + index).val(),lcInt);
            if(!isNaN(quantity)){
               $('#quanNum_' + index).css("border-color", '#AAA');
               return true;
            }
            else {
                $('#quanNum_' + index).css("border-color", "red");
                return false
            }
            break;
        case 'unit_price':
            var lcInt = locale(decimalPoint, thousandSep, 0);
            var unitPrice = parseLcNum($('#unitPrice_' + index).val(),lcInt);
            if(!isNaN(quantity)){
               $('#unitPrice_' + index).css("border-color", '#AAA');
               return true;
            }
            else {
                $('#unitPrice_' + index).css("border-color", "red");
                return false
            }
            break;   
    }
} 

function validateElement(elementId, dataType, checkEmpty){
    switch (dataType) {
        case "integer":
            lcInt   =   locale(decimalPoint, thousandSep, 0);
            return validatePositiveIntegerByLocale($('#' + elementId), lcInt, checkEmpty, '', 'dummy');
            break;
        case "float":
            var lcFloat = locale(decimalPoint, thousandSep, 1);
            return validatePositiveNumberByLocale($('#' + elementId), lcFloat, checkEmpty, '', 'dummy');
            break;
        default:
            return true;
            break;            
    }
}

function calculateMedicineOriginalPrice(index){
	var lcInt     =    locale(decimalPoint, thousandSep, 0);
	var lcFloat = locale(decimalPoint, thousandSep, 1);
	var quantity  =    parseLcNum($('#quanNum_' + index).val(), lcInt);
    var unitPrice =    parseLcNum($('#unitPrice_' + index).val(), lcFloat);
    if (!isNaN(quantity) && !isNaN(unitPrice)) {
        orgPrice    =   quantity * unitPrice;
        $('#orgPrice_' + index).val(orgPrice);
    }
}

function calculateMaterialOriginalPrice(index){
    var lcInt     =    locale(decimalPoint, thousandSep, 0);
    var lcFloat = locale(decimalPoint, thousandSep, 1);
    var quantity  =    parseLcNum($('#matQuanNum_' + index).val(), lcInt);
    var unitPrice =    parseLcNum($('#matUnitPrice_' + index).val(), lcFloat);
    if (!isNaN(quantity) && !isNaN(unitPrice)) {
        orgPrice    =   quantity * unitPrice;
        $('#matOrgPrice_' + index).val(orgPrice);
    }
}

function calculateMedicineInsurancePrice(index){
    var lcInt     =    locale(decimalPoint, thousandSep, 0);
    var lcFloat = locale(decimalPoint, thousandSep, 1);
    var quantity  =    parseLcNum($('#quanNum_' + index).val(), lcInt);
    var unitPrice =    parseLcNum($('#unitInsPrice_' + index).val(), lcFloat);
    if (!isNaN(quantity) && !isNaN(unitPrice)) {
        orgPrice    =   quantity * unitPrice;
        $('#insPrice_' + index).val(orgPrice);
    }
}

function calculateMaterialInsurancePrice(index){
    var lcInt     =    locale(decimalPoint, thousandSep, 0);
    var lcFloat = locale(decimalPoint, thousandSep, 1);
    var quantity  =    parseLcNum($('#matQuanNum_' + index).val(), lcInt);
    var unitPrice =    parseLcNum($('#matUnitInsPrice_' + index).val(), lcFloat);
    if (!isNaN(quantity) && !isNaN(unitPrice)) {
        orgPrice    =   quantity * unitPrice;
        $('#matInsPrice_' + index).val(orgPrice);
    }
}

function calculateMedicinePatientPrice(index){
   var lcFloat = locale(decimalPoint, thousandSep, 1);
   var orgPrice =   parseLcNum($('#orgPrice_' + index).val(), lcFloat);
   var insPrice =   parseLcNum($('#insPrice_' + index).val(), lcFloat);
   if(!isNaN(orgPrice) && !isNaN(insPrice)){
        patPrice    =   orgPrice - insPrice;
        $('#patPrice_' + index).val(patPrice);
   }
}

function calculateMaterialPatientPrice(index){
   var lcFloat = locale(decimalPoint, thousandSep, 1);
   var orgPrice =   parseLcNum($('#matOrgPrice_' + index).val(), lcFloat);
   var insPrice =   parseLcNum($('#matInsPrice_' + index).val(), lcFloat);
   if(!isNaN(orgPrice) && !isNaN(insPrice)){
        patPrice    =   orgPrice - insPrice;
        $('#matPatPrice_' + index).val(patPrice);
   }
}

function isReadyToSubmit(){
    var res =   true;
    $('#medTbl tbody tr').each(function(){
        index   =   $(this).attr('id');
        if( $('#medId_' + index).val() > 0) {
            
            // Validate inputs
            // Quantity number
            if(!validateElement('quanNum_' + index, 'integer', true)
                    || !validateElement('unitPrice_' + index, 'float', true)
                    || !validateElement('orgPrice_' + index, 'float', true)
                    || !validateElement('insPrice_' + index, 'float', true)
                    || !validateElement('patPrice_' + index, 'float', true)) {
                res = false;
            } else {
                $(this).find('input').css("border-color", '#AAA');
            }
        } else {
            $(this).find('input').css("border-color", '#AAA');
        }
    });
    $('#matTbl tbody tr').each(function(){
        index   =   $(this).attr('id');
        if( $('#matId_' + index).val() > 0) {
            // Validate inputs
            // Quantity number
            if(!validateElement('matQuanNum_' + index, 'integer', true)
                    || !validateElement('matUnitPrice_' + index, 'float', true)
                    || !validateElement('matOrgPrice_' + index, 'float', true)
                    || !validateElement('matInsPrice_' + index, 'float', true)
                    || !validateElement('patPrice_' + index, 'float', true)) {
                res =   false;
            } else {
                $(this).find('input').css("border-color", '#AAA');
            }
        } else {
            $(this).find('input').css("border-color", '#AAA');
        }
    });
    return res;
}

function saveInputMedicineMaterial(){
    if(!isReadyToSubmit()) {
        $('#savingStatusMsg').css("color", "red").text(_('Error! Please check the input data')).show();
        setTimeout("clearText('savingStatusMsg')", 10000);
        return;
    }
    showAjaxLoader('inputMedicineLoaderDiv', 'inputMedicineActionButtonDiv', true);
    var sumittedData    =   $('#inputMedicineFrm').formSerialize();
    var medNum  =   $('table#medTbl tbody tr').length;
    var matNum  =   $('table#matTbl tbody tr').length;
    var issueDate   =   $('#issueDateLbx').val();
	$.ajax({
	       type:   "GET",
	       url:    "../TicketMedicine/SaveTicketMedicine?set_ajax_view&ticketId=" + $('#ticketIdHdn').val()+
	               "&medNum=" + medNum + "&matNum=" + matNum + "&issueDate=" + issueDate,
	       data:   sumittedData,
	       dataType:   "json",
	       success:  function(data) {              
                showAjaxLoader('inputMedicineLoaderDiv', 'inputMedicineActionButtonDiv', false);
                $('#savingStatusMsg').css("color", "green").text(_('Save successful')).show();
                setTimeout("clearText('savingStatusMsg')", 10000);
	       }
	   });
}

function clearText(id){
    $('#' + id).text('');
}

function createNewMedicineRow(index){
     newRow  =   "<tr id=\"" + index + "\">";
     newRow  +=  "<td><input type=\"text\" class=\"medName\" name=\"medName_" + index + "\" id=\"medName_" + index + "\" style=\"width: 140px;\" onblur=\"getItemInfo(\'medicine\'," + index + ")\">"
                     + "<input type=\"hidden\" name=\"medId_" + index + "\" id=\"medId_" + index + "\"></td>";
     newRow  +=  "<td><input type=\"text\" name=\"quanNum_" + index + "\" id=\"quanNum_" + index + "\" style=\"width: 25px;\" onblur=\"validateElement(this.id, \'integer\', false)\" onkeypress=\"return allowEnterIntegerNum(event,true)\">"
                     + "&nbsp;<input type=\"text\" name=\"quanTitle_" + index + "\" id=\"quanTitle_" + index + "\" style=\"width: 40px;\"></td>";
     newRow  +=  "<td><input type=\"text\" name=\"unitPrice_" + index + "\" id=\"unitPrice_" + index + "\" style=\"width: 50px;\" onblur=\"validateElement(this.id, \'float\', false)\"></td>";
     newRow  +=  "<td><input type=\"text\" name=\"orgPrice_" + index + "\" id=\"orgPrice_" + index + "\" style=\"width: 60px;\" onblur=\"validateElement(this.id, \'float\', false)\" onfocus=\"calculateMedicineOriginalPrice(" + index + ")\"></td>";
     newRow  +=  "<td><input type=\"text\" name=\"insPrice_" + index + "\" id=\"insPrice_" + index + "\" style=\"width: 60px;\" onblur=\"validateElement(this.id, \'float\', false)\" onfocus=\"calculateMedicineInsurancePrice(" + index + ")\">"
                     + "<input type=\"hidden\" id=\"unitInsUnitPrice_index\" name=\"unitInsPrice_index\"></td>";
     newRow  +=  "<td><input type=\"text\" name=\"patPrice_" + index + "\" id=\"patPrice_" + index + "\" style=\"width: 60px;\" onblur=\"validateElement(this.id, \'float\', false)\" onfocus=\"calculateMedicinePatientPrice(" + index + ")\"></td>";
     newRow  +=  "<td><span id=\"issuePersonName_" + index + "\"></span><input type=\"hidden\" name=\"issuePerson_" + index + "\" id=\"issuePerson_" + index + "\"></td>";
     newRow  +=  "<td><span id=\"doctorName_" + index + "\"></span><input type=\"hidden\" name=\"doctor_" + index + "\" id=\"doctor_" + index + "\"></td>";
     newRow  +=  "<td><a href=\"javascript:clearMedicineRow(" + index + ")\" title=\"" + _('Clear') + "\">" + _('Clear') + "</a></td>";
     newRow  +=  "</tr>";
     return newRow;
}

function createNewMaterialRow(index){
     newRow  =   "<tr id=\"" + index + "\">";
     newRow  +=  "<td><input type=\"text\" class=\"matName\" name=\"matName_" + index + "\" id=\"matName_" + index + "\" style=\"width: 140px;\" onblur=\"getItemInfo(\'material\'," + index + ")\">"
                     + "<input type=\"hidden\" name=\"matId_" + index + "\" id=\"matId_" + index + "\"></td>";
     newRow  +=  "<td><input type=\"text\" name=\"matQuanNum_" + index + "\" id=\"matQuanNum_" + index + "\" style=\"width: 25px;\" onblur=\"validateElement(this.id, \'integer\', false)\" onkeypress=\"return allowEnterIntegerNum(event,true)\">"
                     + "&nbsp;<input type=\"text\" name=\"matQuanTitle_" + index + "\" id=\"matQuanTitle_" + index + "\" style=\"width: 40px;\"></td>";
     newRow  +=  "<td><input type=\"text\" name=\"matUnitPrice_" + index + "\" id=\"matUnitPrice_" + index + "\" style=\"width: 50px;\" onblur=\"validateElement(this.id, \'float\', false)\"></td>";
     newRow  +=  "<td><input type=\"text\" name=\"matOrgPrice_" + index + "\" id=\"matOrgPrice_" + index + "\" style=\"width: 60px;\" onblur=\"validateElement(this.id, \'float\', false)\" onfocus=\"calculateMaterialOriginalPrice(" + index + ")\"></td>";
     newRow  +=  "<td><input type=\"text\" name=\"matInsPrice_" + index + "\" id=\"matInsPrice_" + index + "\" style=\"width: 60px;\" onblur=\"validateElement(this.id, \'float\', false)\" onfocus=\"calculateMaterialInsurancePrice(" + index + ")\">"
                     + "<input type=\"hidden\" id=\"matUnitInsUnitPrice_index\" name=\"matUnitInsPrice_index\"></td>";
     newRow  +=  "<td><input type=\"text\" name=\"matPatPrice_" + index + "\" id=\"matPatPrice_" + index + "\" style=\"width: 60px;\" onblur=\"validateElement(this.id, \'float\', false)\" onfocus=\"calculateMaterialPatientPrice(" + index + ")\"></td>";
     newRow  +=  "<td><span id=\"matIssuePersonName_" + index + "\"></span><input type=\"hidden\" name=\"matIssuePerson_" + index + "\" id=\"matIssuePerson_" + index + "\"></td>";
     newRow  +=  "<td><span id=\"matDoctorName_" + index + "\"></span><input type=\"hidden\" name=\"matDoctor_" + index + "\" id=\"matDoctor_" + index + "\"></td>";
     newRow  +=  "<td><a href=\"javascript:clearMaterialRow(" + index + ")\" title=\"" + _('Clear') + "\">" + _('Clear') + "</a></td>";
     newRow  +=  "</tr>";
     return newRow;
}